package edu.nf.ch06.container;

import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangl
 * @date 2025/4/16
 * 容器工厂
 */
public class ContainerFactory {

    /**
     * 容器，用于存放带有@Component注解的类示例
     */
    private final Map<String, Object> container = new HashMap<>();

    /**
     * 初始化字段注入处理器
     */
    private final FieldInjectHandler injectHandler = new FieldInjectHandler();
    /**
     * 初始化工厂
     * @param packageName
     */
    public ContainerFactory(String packageName) {
        //初始化
        init(packageName);
        //装配注入
        processInject();
    }

    private void init(String packageName) {
        //执行扫描
        ClassInfoList list = ScanUtils.scan(packageName);
        //循环遍历集合中的类，找出带有@Compontent注解的类
        for (ClassInfo classInfo : list) {
            //得到Class对象
            Class<?> clazz = classInfo.loadClass();
            //判断类上是否声明了@Component注解
            if(clazz.isAnnotationPresent(Component.class)) {
                //将带有注解的类示例存放到容器中
                try {
                    Component component = clazz.getAnnotation(Component.class);
                    String name = component.value();
                    Object instance = clazz.getConstructor().newInstance();
                    //保存到容器
                    container.put(name, instance);
                } catch (Exception e) {
                    throw new RuntimeException("New instance fail.",e);
                }
            }
        }
    }

    /**
     * 给所有的Bean执行注入装配
     */
    private void processInject() {
        for(String key : container.keySet()) {
            Object instance = container.get(key);
            //执行对象的注入装配
            injectHandler.handle(instance, this);
        }
    }

    /**
     * 根据名称从容器获取对象
     * @param name 容器中的key
     * @return 对应的实例
     * @param <T>
     */
    public <T> T getBean(String name) {
        if(container.containsKey(name)) {
            return (T) container.get(name);
        }
        throw new RuntimeException("No such bean: " + name);
    }
}